package com.atguigu.day06;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

// 开窗口，将迟到数据发送到侧输出流
public class Example5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .addSource(new SourceFunction<String>() {
                    @Override
                    public void run(SourceContext<String> ctx) throws Exception {
                        ctx.collectWithTimestamp("hello", 1000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("hello", 2000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(1999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("hello", 1000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(4999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("hello", 1000L);
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .keyBy(r -> r)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                // 将迟到的且对应窗口已经被销毁的数据发送到侧输出流
                .sideOutputLateData(new OutputTag<String>("late-event") {
                })
                .process(new ProcessWindowFunction<String, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<String> elements, Collector<String> out) throws Exception {
                        out.collect("窗口：" + context.window().getStart() + "~" + context.window().getEnd() + "" +
                                "中共有" + elements.spliterator().getExactSizeIfKnown());
                    }
                });

        result.print("主流：");
        result.getSideOutput(new OutputTag<String>("late-event"){}).print("侧输出流：");

        env.execute();

    }
}

